<?php

namespace app\wx\service;
use think\Db;
use encryption\encryption;

/**
 * 管理员表操作数据库
 */
class AdminService{
    const TABLE = 'admin';

    /**
     * 查询条件
     * @param array   $data   参数
     * @return array 
     */
    static private function map($data){
        $map = [];
        if($data['id']){
            $map['id'] = $data['id'];
        }
        if($data['name']){
            $map['name'] = $data['name'];
        }
        if($data['number']){
            $map['number'] = $data['number'];
        }
        if($data['phone']){
            $map['phone'] = $data['phone'];
        }
        if($data['email']){
            $map['email'] = $data['email'];
        }
        if($data['status']){
            $map['status'] = $data['status'];
        }
        if($data['start_time'] && $data['end_time']){ //交易时间
            $map['create_time'] = array(array("egt",$data['start_time']),array("elt",$data['end_time']));
        }
        return $map;
    }

    /**
     * 查询管理员
     * @param array $param  查询条件
     * @param int $page  页面
     * @param int $limit 页面显示数量
     * @param string $field 查询字段
     * @return array
     */

    static public function findAdmin($param, $pp = 1, $num = 10,  $field = '*'){
        //查询条件
        $map = self::map($param);
        $count = Db::name(self::TABLE)->where($map)->count();
        //计算pp
        $pp = ceil($count / $num) < $pp ? ceil($count / $num) : $pp;
        //查询数据
        $list = Db::name(self::TABLE)->where($map)->order("id desc")->page($pp,$num)->field($field)->select();
        return [
            'list' => $list,
            'count' => $count,
            'pp' => $pp
        ];
    }

    /**
     * 添加管理员
     * @param array 待添加数据
     * @return int 返回添加ID
     */
    static public function add($param)
    {
        $salt = Encryption::salt(); //加严密钥
        $pwd = Encryption::enMd5($param['pwd'],$salt);
        $param['salt'] = $salt;
        $param['pwd'] = $pwd;
        $param['create_time'] = date('Y-m-d H:i:s');
        $id = Db::name(self::TABLE)->insertGetId($param);
        if(!$id){
            error('数据添加失败，mysql异常!');
        }
        return $id;
    }

    /**
     * 修改管理员
     * @param array 待添加数据
     * @return void
     */
    static public function edit($param)
    {
        $param['update_time'] = date('Y-m-d H:i:s');
        $id = $param['id'];
        $result = Db::name(self::TABLE)->where('id',$id)->update($param);
        if(!$result){
            error('数据修改失败，mysql异常!');
        }
    }
}